﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using RxxApi.Common.Helper;
using RxxApi.Common.Seed;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RxxApi.Extensions.HostedService;

public sealed class SeedDataHostedService : IHostedService
{
    private readonly MyContext _myContext;
    private readonly string _webRootPath;
    private readonly ILogger<SeedDataHostedService> _logger;
    public SeedDataHostedService(MyContext myContext, IWebHostEnvironment webHostEnvironment,ILogger<SeedDataHostedService> logger)
    {
        _myContext = myContext;
        _webRootPath = webHostEnvironment.WebRootPath;
        _logger = logger;
    }
    public async Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Start Initialization Db Seed Service!");
        await DoWork();
    }
    private async Task DoWork()
    {
        try
        {
           await DBSeed.SeedAsync(_myContext, _webRootPath);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error occured seeding the Database.");
            throw;
        }
    }
    public Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Stop Initialization Db Seed Service!");
        return Task.CompletedTask;
    }
}
